package com.atguigu.consumer;

import com.alibaba.fastjson.JSON;
import com.atguigu.client.PaymentFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class OrderConsumer {
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentFeignClient paymentFeignClient;
    @RabbitListener(queues = MqConst.CANCEL_ORDER_QUEUE)
    public void cancelOrder(Long orderId, Message message, Channel channel) throws Exception {
        if (orderId != null) {
            //查询订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            //如果订单为未支付
            if (orderInfo != null && orderInfo.getOrderStatus().equals(ProcessStatus.UNPAID.getOrderStatus().name())) {
                //关闭订单信息
                orderInfoService.updateOrderStatus(orderInfo, ProcessStatus.CLOSED);
                PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                //如果有支付订单信息
                if (paymentInfo!=null && paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
                    rabbitTemplate.convertAndSend(MqConst.CLOSE_PAYMENT_EXCHANGE, MqConst.CLOSE_PAYMENT_ROUTE_KEY, orderId);
                    //如果阿里系统创建了交易 则关闭阿里内部交易
                    boolean flag = paymentFeignClient.queryAlipayTrade(orderId);
                    if(flag){
                        paymentFeignClient.closeAlipayTrade(orderId);
                    }
                }
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }

    //2.支付成功之后更新订单信息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.PAY_ORDER_QUEUE,durable = "false"),
            exchange = @Exchange(value = MqConst.PAY_ORDER_EXCHANGE,durable = "false",autoDelete = "true"),
            key = {MqConst.PAY_ORDER_ROUTE_KEY}
    ))
    public void updateOrderAfterPaySucess(Long orderId, Message message , Channel channel) throws Exception{
        if (orderId!=null){
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            //这个订单为未支付
            if (orderInfo!=null && orderInfo.getOrderStatus().equals(ProcessStatus.UNPAID.getOrderStatus().name())){
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.PAID);
                //发送消息通知仓库系统减库存
                orderInfoService.sendMsgToWarehouse(orderInfo);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    //3.接收库存系统发过来的消息！
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.SUCCESS_DECREASE_STOCK_QUEUE,durable = "false"),
            exchange = @Exchange(value = MqConst.SUCCESS_DECREASE_STOCK_EXCHANGE,durable = "false",autoDelete = "true"),
            key = {MqConst.SUCCESS_DECREASE_STOCK_ROUTE_KEY}
    ))
    public void updateOrderStatus(String msgJson, Message message , Channel channel) throws Exception{
        if (!StringUtils.isEmpty(msgJson)){
            Map map = JSON.parseObject(msgJson, Map.class);
            // 获取对应的数据
            String orderId = (String) map.get("orderId");
            String status = (String) map.get("status");
            OrderInfo orderInfo = orderInfoService.getOrderInfo(Long.parseLong(orderId));
            if ("DEDUCTED".equals(status)){
                // 减库存成功！
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.WAITING_DELEVER);
            }else {
                // 减库存失败！超卖
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


}
